#include "CAddStuInfoDialog.h"
#include "CStuInfo.h"
#include "ui_CAddStuInfoDialog.h"

#include <QMessageBox>

CAddStuInfoDialog::CAddStuInfoDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CAddStuInfoDialog),
    m_isUpdate(false)
{
    ui->setupUi(this);
    //初始为添加信息
    m_isUpdate = false;
    //初始化界面
    initUi();
}

CAddStuInfoDialog::~CAddStuInfoDialog()
{
    delete ui;
}

void CAddStuInfoDialog::initUi()
{
    //学号提示信息
    ui->edit_Id->setPlaceholderText("请输入四位数字的学号");
    // 创建正则表达式对象
    QRegExp regId("^[0-9]{4}$");
    // 绑定到输入框
    ui->edit_Id->setValidator(new QRegExpValidator(regId, this));

    //姓名提示信息
    ui->edit_Name->setPlaceholderText("请输入中文姓名");
    // 创建正则表达式对象
    QRegExp regName("^[\u4E00-\u9FA5]+$");
    // 绑定到输入框
    ui->edit_Name->setValidator(new QRegExpValidator(regName, this));



    //性别
    ui->cmb_Sex->addItem("男");
    ui->cmb_Sex->addItem("女");

    //手机号提示信息
    ui->edit_Phone->setPlaceholderText("请输入十一位数字的手机号");
    // 创建正则表达式对象
    QRegExp regPhone("^[1-9][0-9]{10}$");
    // 绑定到输入框
    ui->edit_Phone->setValidator(new QRegExpValidator(regPhone, this));

    //cet4
    ui->spb_Cet4->setRange(0, 750);

    //gpa
    ui->dpb_Gpa->setRange(0.00, 4.00);
}

bool CAddStuInfoDialog::clearData()
{
    ui->edit_Id->clear();
    ui->edit_Name->clear();
    ui->edit_Phone->clear();
    ui->spb_Cet4->clear();
    ui->dpb_Gpa->clear();

    return true;
}

void CAddStuInfoDialog::on_btn_Confirm_clicked()
{
    //验证输入信息的合法性
    //Id合法性
    int lengthId = ui->edit_Id->text().size();
    if(lengthId != 4)
    {
        QMessageBox::information(this, "提示", "学号输入不合规!");
        return;
    }
    //Phone合法性
    int lengthPhone = ui->edit_Phone->text().size();
    if(lengthPhone != 11)
    {
        QMessageBox::information(this, "提示", "手机号码输入不合规!");
        return;
    }

    //从输入内容中获取信息
    int id = ui->edit_Id->text().toInt();
    QString name = ui->edit_Name->text();
    QString sex = ui->cmb_Sex->currentText();
    QString phone = ui->edit_Phone->text();
    int cet4 = ui->spb_Cet4->value();
    double gpa = ui->dpb_Gpa->value();
    CStuInfo stuInfo;
    stuInfo.setdata(id, name, sex, phone, cet4, gpa);

    //发送信号给主界面
    if(m_isUpdate)
    {
        emit sig_updateInfo(stuInfo);
    }
    else
    {
        emit sig_addInfo(stuInfo);
        //清空文本框数据
        clearData();
    }

}

void CAddStuInfoDialog::on_btn_Cancel_clicked()
{
    close();
}

bool CAddStuInfoDialog::isUpdate() const
{
    return m_isUpdate;
}

void CAddStuInfoDialog::setIsUpdate(bool isUpdate)
{
    m_isUpdate = isUpdate;
}

bool CAddStuInfoDialog::display(int id, QString name, QString sex, QString phone, int cet4, double gpa)
{
    ui->edit_Id->setText(QString("%1").arg(id, 4, 10,QLatin1Char('0')));
    ui->edit_Id->setReadOnly(true);
    ui->edit_Name->setText(name);
    ui->cmb_Sex->setCurrentText(sex);
    ui->edit_Phone->setText(phone);
    ui->spb_Cet4->setValue(cet4);
    ui->dpb_Gpa->setValue(gpa);
    return true;
}
